<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Inventario {
	
    //Inicializa pond en costos
	function inicial($codigo){
        
      $CI =& get_instance();
        
      $mSQL_1 = $CI->db->query("SELECT fecha,cantidad,codigo,pond,ubica FROM costos WHERE origen='0F' AND codigo='$codigo' GROUP BY ubica ORDER BY fecha ASC");
        
       foreach($mSQL_1->result() as $items ){

            $CI->db->query("UPDATE costos SET pond=$items->pond WHERE codigo='$items->codigo' AND fecha>='$items->fecha' AND origen<>'0F' AND ubica='$items->ubica'"); 
	
		} 
    }
    
    //Saldos de costos
    function saldos($codigo){
        
        $CI =& get_instance();
        
        $mSQL_1=$CI->db->query("SELECT codigo,ubica FROM costos as a WHERE codigo='$codigo' GROUP BY ubica");
        
        foreach ($mSQL_1->result() AS $items){
            
            $saldo=$CI->datasis->dameval("SELECT cantidad FROM costos as a 
            WHERE codigo='$items->codigo' AND origen ='0F'  AND ubica='$items->ubica'
            ORDER BY fecha DESC");
            
            $idcosto=$CI->datasis->dameval("SELECT idcosto FROM costos as a 
            WHERE codigo='$items->codigo' AND origen ='0F'  AND ubica='$items->ubica'
            ORDER BY fecha DESC");
            
            if(!empty($saldo)){
                $tmonto=$saldo;
                $CI->db->query("UPDATE costos SET saldo=$tmonto WHERE codigo='$items->codigo' AND origen ='0F' AND idcosto='$idcosto' and ubica='$items->ubica'");
            }else{
                $tmonto=0;
            }
            
            
            
            //$mSQL=$CI->db->query("SELECT a.ubica,codigo,idcosto,IF(origen IN ('2C','5C','TE','0F','NC'),cantidad,0) as d,
            //IF(origen='3I',cantidad,IF(origen='TS',cantidad*-1,0))c
            //FROM costos as a WHERE codigo='$codigo' and ubica='$items->ubica' ORDER BY a.ubica ,fecha,factura ASC");
            
            $mSQL=$CI->db->query("SELECT origen,a.ubica,codigo,idcosto,IF(origen IN ('2C','5C','TE','NC','CE'),cantidad,0) as d,
            IF(origen IN ('3I','NCP'),cantidad,IF(origen IN ('TS','CS'),cantidad*-1,0))c
            FROM costos as a WHERE origen<>'0F' and codigo='$codigo' and ubica='$items->ubica'  ORDER BY a.ubica ,fecha,factura ASC");
        
            foreach ($mSQL->result() AS $items){
                
                $tmonto+=$items->d-$items->c;
                
                $CI->db->query("UPDATE costos SET saldo=$tmonto WHERE idcosto='$items->idcosto' AND origen <> '0F'");
        
            }
            
            
        }
        
    }
    
    function costeo($codigo){
        
        $CI =& get_instance();
		
        $mSQL=$CI->db->query("SELECT  fecha FROM costos WHERE codigo='$codigo' AND  origen <> '0F' GROUP BY MONTH(fecha)"); 
		
		foreach ($mSQL->result() AS $items){
            
        $date = strtotime($items->fecha);        
        $recep=date('Y-m',$date);
        $fechad=$recep.'-01';
        //echo 'fecha'.$items->fecha;

        $del="DELETE FROM sinvcostos WHERE MONTH(fecha)=MONTH('$fechad') AND codigo='$codigo'";
        //echo $del;
        $CI->db->query($del);
        
        $query_2=$CI->db->query("SELECT a.codigo,IF(
        (SELECT costo FROM sinvcostos as b WHERE a.codigo=b.codigo AND MONTH(fecha)=IF(MONTH('$fechad')=1,12,MONTH('$fechad')) ORDER BY fecha DESC LIMIT 1 )
        IS NULL,(SELECT costo FROM sinvcostos as b  WHERE a.codigo=b.codigo AND MONTH(fecha)=IF(MONTH('$fechad')=1,12,MONTH('$fechad')-1) ORDER BY fecha DESC LIMIT 1 ),
        (SELECT costo FROM sinvcostos as b WHERE a.codigo=b.codigo AND MONTH(fecha)=IF(MONTH('$fechad')=1,12,MONTH('$fechad')) ORDER BY fecha DESC LIMIT 1 )
        ) costo,LAST_DAY('$fechad') fecha 
        FROM sinv AS a WHERE a.codigo='$codigo'");
                
        foreach($query_2->result() as $items ){
        
        $CI->db->query("INSERT INTO sinvcostos (fecha,costo,codigo,ultimo)VALUES
             ('$items->fecha','$items->costo','$items->codigo','$items->costo')");
        
        }
		
		//Compras
        $query=$CI->db->query("SELECT a.fecha as ffecha,transac,recep as compra,DATE_ADD(recep,INTERVAL (-1) DAY)recep,a.codigo, cantidad,IF(b.moneda='01',ROUND(a.costo/b.cambio,2),a.costo)costo
		FROM itscst as a 
		JOIN scst as b ON a.control=b.control 
		WHERE recep BETWEEN '$fechad' AND LAST_DAY('$fechad') AND a.codigo='$codigo'");//AND codigo='VTK-500M'
        
		foreach($query->result() as $items ){
            
            $delete="DELETE FROM sinvcostos WHERE codigo='$items->codigo' and fecha='$items->compra' AND transac='$items->transac'";
            $CI->db->query($delete);
            //echo $delete;
            
            $fechainv=$CI->datasis->dameval("SELECT fecha FROM costos as a
            where origen='0F' AND codigo='$items->codigo' ORDER BY fecha DESC LIMIT 1");
            
            IF(empty($fecha))$fecha="2013-12-31";
            
            $chek=$CI->datasis->dameval("SELECT COUNT(*) FROM sinvcostos WHERE codigo='$items->codigo' and fecha='$items->compra'");
            
            IF($chek>0){
                
                $fecha_final="$items->compra";
                
            }else{
                
                $fecha_final="$items->recep";
            }
            
            $CI->db->query("DROP TABLE IF EXISTS ccostosii");
            
            //Existencias
            $mSQL_1="CREATE TABLE  IF NOT EXISTS ccostosii ENGINE=MyISAM
            SELECT a.origen,a.codigo,SUM(a.cantidad)AS cantidad FROM costos as a
            where origen <> '3I' AND fecha BETWEEN '$fechainv'  AND '$fecha_final' AND codigo='$items->codigo' group by codigo
            UNION 
            SELECT a.origen,a.codigo,SUM(a.cantidad)*-1 AS cantidad FROM costos as a
            where origen = '3I' AND fecha BETWEEN '$fechainv'  AND '$fecha_final'  AND codigo='$items->codigo' group by codigo";
            //echo $mSQL_1;
            
            $CI->db->query($mSQL_1);
		
            $existen=$CI->datasis->dameval("SELECT SUM(cantidad) FROM ccostosii WHERE codigo='$items->codigo'");
			            
            IF($chek>0){
                
                $ultimo=$CI->datasis->dameval("SELECT costo FROM sinvcostos WHERE codigo='$items->codigo' AND  fecha='$items->compra'
                ORDER BY fecha DESC limit 1");
            
            }ELSE{
                
                $ultimo=$CI->datasis->dameval("SELECT costo FROM sinvcostos WHERE codigo='$items->codigo' AND  fecha<'$items->compra'
                ORDER BY fecha DESC limit 1");
            
            }
            
            $valor_costeo=((($existen*$ultimo)+($items->cantidad*$items->costo))/($existen+$items->cantidad));
            
            //echo 'codigo:'.$items->codigo.'</br>';
            //echo 'existen:'.$existen.'</br>';
            //echo 'ultimo:'.$ultimo.'</br>';
            //echo 'cantidad:'.$items->cantidad.'</br>';
            //echo 'costo:'.$items->costo.'</br>';
            //echo 'valor:'.$valor_costeo.'</br>';
            
            //$mSQL="UPDATE sitems AS a SET costo=ROUND($valor_costeo,2)
            //WHERE a.codigo='$items->codigo' and a.id=(SELECT id FROM sfac as b where a.id=b.id and fecha >='$items->compra')";
            ////echo $mSQL;
            //$CI->db->query($mSQL);
            
            $CI->db->query("INSERT INTO sinvcostos (ffecha,transac,fecha,costo,codigo,existen,ultimo,compra,pcompra)VALUES
             ('$items->ffecha','$items->transac','$items->compra',ROUND($valor_costeo,2),'$items->codigo','$existen','$ultimo','$items->cantidad','$items->costo')");

             //$CI->db->query("UPDATE costos as a SET pond=(SELECT ROUND(costo,2) FROM sinvcostos as b WHERE b.fecha='20131231' and a.codigo=b.codigo) where a.codigo='$items->codigo' ");
             
             $CI->db->query("UPDATE sinvcostos SET  costo=ROUND($valor_costeo,2),
             codigo='$items->codigo',existen='$existen',ultimo='$ultimo',compra='$items->cantidad',pcompra='$items->costo'
             WHERE codigo='$items->codigo' AND fecha=LAST_DAY('$fechad')");
             
             $CI->db->query("UPDATE costos SET pond=ROUND($valor_costeo,2)
             WHERE codigo='$items->codigo' AND fecha>='$items->compra' AND origen<>'2C'");
             
             $CI->db->query("UPDATE costos SET pond=monto
             WHERE codigo='$items->codigo' AND fecha>='$items->compra' AND origen='2C'");
             
             $CI->db->query("UPDATE sinv SET pond=ROUND($valor_costeo,2) , ultimo='$items->costo',formcal='P',
             utilidad1=(base1-ROUND($valor_costeo,2)),margen1=((base1-ROUND($valor_costeo,2))*100)/ROUND($valor_costeo,2),
             utilidad2=(base2-ROUND($valor_costeo,2)),margen2=((base2-ROUND($valor_costeo,2))*100)/ROUND($valor_costeo,2),
             utilidad3=(base3-ROUND($valor_costeo,2)),margen3=((base3-ROUND($valor_costeo,2))*100)/ROUND($valor_costeo,2),
             utilidad4=(base4-ROUND($valor_costeo,2)),margen4=((base4-ROUND($valor_costeo,2))*100)/ROUND($valor_costeo,2)
             WHERE codigo='$items->codigo'");
             
             $query_5=$CI->db->query("SELECT a.numero,fecha,b.codigo FROM ssal as a 
             JOIN itssal as b on a.numero=b.numero WHERE fecha>='$items->compra' AND codigo='$items->codigo' AND tipo NOT IN ('R')");
             
             foreach($query_5->result() as $items ){
                 
                $costop=$CI->datasis->dameval("SELECT pond FROM costos WHERE fecha<='$items->fecha' AND codigo='$items->codigo' ORDER BY fecha DESC LIMIT 1");
                
                IF(empty($costop)){$costo=0;}else{$costo=$costop;}
                 
                $CI->db->query("UPDATE itssal as a SET costo='$costo' WHERE codigo='$items->codigo' and numero='$items->numero'");
             }
		
		}
        
		$CI->db->query("DROP TABLE IF EXISTS ccostosii");				

        }
    }
    function sp_costos($id='',$tipo=''){
	
			
			 switch ($tipo) {
				
				case '3I': //guia
				$this->_3i($id);
				//return '3i';
				break;
				
				case '2C': //compra
				$this->_2c($id);
				//return '2c';
				break;
				
				case '0F': //inventario fisico
				$this->_of($id);
				break;
				
				case 'A': //ajustes de entrada y salidad
				$this->_a($id);
				break;
				
				case 'NC': //nota de credito cliente
				$this->_nc($id);
				break;
 
				case 'NCP': //nota de credito proveedor
				$this->_ncp($id);
				break;
				case 'T': //transferencias
				$this->_t($id);
				break;
				
                case 'AT': //ordenes de compra
                $this->_at($id); 
                break;
                
                case 'CT'://ordenes de importacion 
                $this->_ct($id);
                break;
                
                case 'C': //conversiones
                $this->_c($id);
                break;
                
				default:   return('NINGUN TIPO SELECCIONADO'); 	
			}
		
		
	}
	function _crears($mes_ano,$alma){	
		$CI =& get_instance();
		$CI->db->query("INSERT INTO saldosm SELECT codigo as codigo,'$mes_ano' as fecha,'$alma' alma,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 
		FROM sinv where activo='S' AND tipo='01' and codigo in ('005-002-F81','6090-P')");
		echo 'REALIZADO CORRECTAMENTE PARA LA FECHA DE '.$mes_ano;
	}
	function _rcalcula($codigo,$fecha,$tipo,$tregis,$alma){	
		
		$CI =& get_instance();
		
		$mes=substr($fecha, 4, 2);
		$ano=substr($fecha, 0, 4);
		
		IF($tipo!='AS'){
			$campo=$tipo;
		}else{
			$campo='AAS';
		};
		
		$o=1;
		while ($o <= 5) {
			
			$alma=STR_PAD($o,4,0,STR_PAD_LEFT);
			$CI->db->query("UPDATE saldosm as a SET 
			mese=IF((SELECT ROUND(SUM(egreso),2) tot FROM costos as c WHERE DATE_FORMAT(c.fecha,'%Y%m')='$fecha' AND c.codigo='$codigo' and c.ubica='$alma')IS NULL,0,(SELECT ROUND(SUM(egreso),2) tot FROM costos as c WHERE DATE_FORMAT(c.fecha,'%Y%m')='$fecha' AND c.codigo='$codigo' and c.ubica='$alma')), 
			mesi=IF((SELECT ROUND(SUM(ingreso),2) tot FROM costos as c WHERE DATE_FORMAT(c.fecha,'%Y%m')='$fecha' AND c.codigo='$codigo' and c.ubica='$alma')IS NULL,0,(SELECT ROUND(SUM(ingreso),2) tot FROM costos as c WHERE DATE_FORMAT(c.fecha,'%Y%m')='$fecha' AND c.codigo='$codigo' and c.ubica='$alma')), 
			$campo=IF((SELECT ROUND(SUM($tregis),2) tot FROM costos as c WHERE c.origen='$tipo' AND DATE_FORMAT(c.fecha,'%Y%m')='$fecha' AND c.codigo='$codigo' and c.ubica='$alma')IS NULL,0,(SELECT ROUND(SUM($tregis),2) tot FROM costos as c WHERE c.origen='$tipo' AND DATE_FORMAT(c.fecha,'%Y%m')='$fecha' AND c.codigo='$codigo' and c.ubica='$alma')) 
			WHERE a.codigo='$codigo' and a.fecha='$fecha' and a.alma='$alma'");	
			
			$o++;
		}
		
			
		while ( $mes <= 12) {
			
			$o=1;
			while ($o <= 5) {
			    $alma=STR_PAD($o,4,0,STR_PAD_LEFT);
				$fmes=  str_pad($mes, 2, "0", STR_PAD_LEFT);
				$ffecha=$ano.$fmes;
				$ffecha_ant=$ffecha.'01';
				//echo 'Fecha :'.$ffecha.' ALMA '.$alma.' Codigo '.$codigo.'</BR>';
				$acumulai=$CI->datasis->dameval("SELECT ROUND(acumulai,2) FROM saldosm WHERE codigo='$codigo' AND fecha=DATE_FORMAT(DATE_ADD('$ffecha_ant',INTERVAL -1 MONTH),'%Y%m') and alma='$alma'");
				$acumulae=$CI->datasis->dameval("SELECT ROUND(acumulae,2) FROM saldosm WHERE codigo='$codigo' AND fecha=DATE_FORMAT(DATE_ADD('$ffecha_ant',INTERVAL -1 MONTH),'%Y%m') and alma='$alma'");
			
				$CI->db->query("UPDATE saldosm SET iniciali='$acumulai',iniciale='$acumulae' WHERE codigo='$codigo' AND fecha='$ffecha' and alma='$alma'");
				$CI->db->query("UPDATE saldosm as a SET acumulai=iniciali+mesi,acumulae=iniciale+mese WHERE a.codigo='$codigo' and a.fecha='$ffecha' and alma='$alma'");
				$CI->db->query("UPDATE saldosm as a SET saldo=acumulai-acumulae WHERE a.codigo='$codigo' and a.fecha='$ffecha'and alma='$alma'");
				$o++;
			}
		    
		    $mes++;
		}
		
		
		$o=1;
		while ($o <= 5) {
			
		$ano_ultimo=$ano.'12';
		$alma=STR_PAD($o,4,0,STR_PAD_LEFT);
		
		$existen_alma=$CI->datasis->dameval("SELECT saldo FROM saldosm WHERE codigo='$codigo' and alma='$alma' and fecha='$ano_ultimo'");
		$CI->db->query("UPDATE itsinv SET existen='$existen_alma' WHERE codigo='$codigo' AND alma='$alma'");
		
		$existen_tot=$CI->datasis->dameval("SELECT sum(existen) FROM itsinv WHERE codigo='$codigo' GROUP BY codigo");
		$CI->db->query("UPDATE sinv SET existen='$existen_tot' WHERE codigo='$codigo'");
		
		$o++;
		}
		
		//UPDATE costos as a set costomn=(SELECT costomn from sinvcostos as b where a.codigo=b.codigo and fecha='20131231'),
		//costome=(SELECT costome from sinvcostos as b where a.codigo=b.codigo and fecha='20131231')
		//where ubica='0001';
		
		//UPDATE saldosm as a set costomn=(SELECT costomn from sinvcostos as b where a.codigo=b.codigo and fecha='20131231'),
		//costome=(SELECT costome from sinvcostos as b where a.codigo=b.codigo and fecha='20131231')
		//where ubica='0001';
					
	}
	function _costos($codigo,$alma,$fecha,$origen,$id){
		
		$CI =& get_instance();
		
		$costomn=$CI->datasis->dameval("SELECT costomn FROM costos  WHERE codigo='$codigo' AND fecha<='$fecha'  AND idfactura<>'$id' AND origen<>'$origen' ORDER BY fecha DESC LIMIT 1");
		$costome=$CI->datasis->dameval("SELECT costome FROM costos  WHERE codigo='$codigo' AND fecha<='$fecha'   AND idfactura<>'$id' AND origen<>'$origen' ORDER BY fecha DESC LIMIT 1");
		
		//$row= $mSQL->row();
		//$costomn=$row->costomn;
		//$costome=$row->costome;
		//AND ubica='$alma'
		$CI->db->query("UPDATE costos as a SET costomn='$costomn',costome='$costome',costeomn='$costomn',costeome='$costome'
		WHERE a.codigo='$codigo' AND a.idfactura='$id' AND a.origen='$origen'");

	}
	function _3i($id){
		
		$CI =& get_instance();
		$CI->db->query("DELETE FROM costos WHERE idfactura='$id' AND origen='3I'");
		$CI->db->query("INSERT INTO costos  SELECT  c.moneda,c.cambio,c.fecha,c.almacen as ubica,
		c.almacen as ubica2,d.codigo ,'3I' as origen,d.nguia, d.remision as idfactura,
		0 ingreso,d.cantidad egreso,c.factura,0,0,0,0,0,0,0
		FROM despachos as d
		JOIN remision as c on d.remision=c.id
		WHERE c.tipo_doc='FC' AND c.id='$id'");
				
		$mSQL=$CI->db->query("SELECT b.almacen,codigo,DATE_FORMAT(b.fecha,'%Y%m') fecha,b.fecha as fechac
		FROM despachos as a 
		JOIN remision as b on a.remision=b.id
		WHERE  a.remision='$id'");
		
		foreach($mSQL->result() as $items ){
				
			$this->_rcalcula("$items->codigo","$items->fecha","3I","egreso","$items->almacen");
			$this->_costos("$items->codigo","$items->almacen","$items->fechac","3I","$id");
		}

	}
	function _2c($id){
		
		$CI =& get_instance();		
		$CI->db->query("DELETE FROM costos WHERE idfactura='$id' AND origen='2C'");
		$CI->db->query("INSERT INTO costos SELECT c.moneda,c.cambio,c.recep,c.depo as ubica,c.depo as ubica2,a.codigo,'2C' as origen,a.numero,a.control as idfactura,
		a.cantidad ingreso,0 egreso,c.orden,0,0,0,0,0,0,0
		FROM itscst as a
		JOIN sinv as b on a.codigo=b.codigo
		join scst as c on a.control=c.control
		where c.control='$id' AND b.tipo='01'");
				
		$mSQL=$CI->db->query("SELECT * FROM scst_por WHERE id='$id'");
		
		foreach($mSQL->result() as $items ){
				
			$this->_rcalcula("$items->codigo","$items->fecha","2C","ingreso","$items->almacen");
		}
		
	}
	function _of($id){
		
		//$CI->db->query("SELECT  (SELECT moneda from sfac as s where s.numero=d.factura LIMIT 1) moneda,
		//(SELECT cambio FROM cambio as f WHERE c.fecha=f.fecha LIMIT 1)cambio,c.fecha,c.almacen as ubica,
		//c.almacen as ubica2,d.codigo ,'3I' as origen,d.nguia, d.remision as idfactura,
		//0 ingreso,d.cantidad egreso
		//FROM despachos as d
		//JOIN sinv as b on d.codigo=b.codigo
		//JOIN remision as c on d.remision=c.id
		//WHERE c.id='$id'");
	}
	function _a($id){
		
		$CI =& get_instance();
		$CI->db->query("DELETE FROM costos WHERE idfactura='$id' AND origen IN ('AS','AE','AR')");
		$CI->db->query("INSERT INTO costos  SELECT c.moneda,c.cambio,c.fecha,c.almacen as ubica,c.almacen as ubica2,a.codigo,IF(c.tipo='S','AS',IF(c.tipo='R','AR','AE')) as origen, 
		a.numero,a.numero as idfactura,IF(c.tipo='E',a.cantidad,0)ingreso,IF(c.tipo IN ('S','R'),a.cantidad,0)egreso,c.numero,0,0,0,0,0,0,0
		FROM itssal as a
		join ssal as c on a.numero=c.numero
		WHERE tipo_doc='FC' AND c.numero='$id'");
		
		$mSQL=$CI->db->query("SELECT c.tipo,c.almacen,codigo,DATE_FORMAT(c.fecha,'%Y%m') fecha,IF(c.tipo='S','AS',IF(c.tipo='R','AR','AE')) as origen,c.fecha as fechac
		IF(c.tipo in ('R','S'),'egreso','ingreso')caso
		FROM itssal as a
		join ssal as c on a.numero=c.numero
		WHERE c.numero='$id'");
		
		foreach($mSQL->result() as $items ){
				
			$this->_rcalcula("$items->codigo","$items->fecha","$items->origen","$items->caso","$items->almacen");
			$this->_costos("$items->codigo","$items->almacen","$items->fechac","$items->origen","$id");
		}
		
	}
	function _nc($id){
		
		$CI =& get_instance();
		$CI->db->query("DELETE FROM costos WHERE idfactura='$id' AND origen='NC'");
		$CI->db->query("INSERT INTO costos  SELECT c.moneda,c.cambio,c.fecha,c.almacen as ubica,c.almacen as ubica2,d.codigo ,'NC' as origen, 
		c.numero, c.id as idfactura,d.cana ingreso,0 egreso,c.factura,0,0,0,0,0,0,0
		FROM itnotascc as d
		JOIN notascc as c on d.id=c.id
		JOIN sinv as b on d.codigo=b.codigo
		WHERE  tipo_doc='NC' AND c.id='$id'");
		
		$mSQL=$CI->db->query("SELECT c.almacen,codigo,DATE_FORMAT(c.fecha,'%Y%m') fecha,c.fecha as fechac
		FROM itnotascc as d
		JOIN notascc as c on d.id=c.id
		WHERE c.id='$id'");
		
		foreach($mSQL->result() as $items ){
				
			$this->_rcalcula("$items->codigo","$items->fecha","NC","ingreso","$items->almacen");
			$this->_costos("$items->codigo","$items->almacen","$items->fechac","NC","$id");
		}
		
		
	}
	function _ncp($id){
		$CI =& get_instance();
		$CI->db->query("DELETE FROM costos WHERE idfactura='$id' AND origen='NCP'");
		$CI->db->query("INSERT INTO costos  SELECT c.moneda,c.cambio,c.fecha,c.almacen as ubica,c.almacen as ubica2,d.cuenta ,
		'NCP' as origen, c.numero, c.id as idfactura,0 ingreso, d.cana egreso,c.numero,0,0,0,0,0,0,0
		FROM itnotascp as d
		JOIN sinv as b on d.cuenta=b.codigo
		JOIN notascp as c on d.id=c.id
		WHERE b.tipo='01' and c.id='$id'");
		
		$mSQL=$CI->db->query("SELECT c.almacen,b.codigo,DATE_FORMAT(c.fecha,'%Y%m') fecha,c.fecha as fechac
		FROM itnotascp as d
		JOIN sinv as b on d.cuenta=b.codigo
		JOIN notascp as c on d.id=c.id
		WHERE b.tipo='01' and c.id='$id'");
		
		foreach($mSQL->result() as $items ){
				
			$this->_rcalcula("$items->codigo","$items->fecha","NCP","egreso","$items->almacen");
			$this->_costos("$items->codigo","$items->almacen","$items->fechac","NCP","$id");
		}
	}
	function _t($id){
		$CI =& get_instance();
		$CI->db->query("DELETE FROM costos WHERE idfactura='$id' AND origen IN ('TE','TS')");
		$CI->db->query("INSERT INTO costos SELECT c.moneda,c.cambio,c.fecha,c.recibe as ubica,c.envia as ubica2,d.codigo ,'TE' as origen,c.numero, c.numero as idfactura,
		d.cantidad ingreso,0 egreso,c.numero,0,0,0,0,0,0,0
		FROM itstra as d
		JOIN stra as c on d.numero=c.numero
		WHERE  envia<>'INFI'  and tipo_doc='FC' and c.numero='$id'
		UNION
		SELECT c.moneda,c.cambio,c.fecha,c.envia as ubica,c.recibe as ubica2,d.codigo ,'TS' as origen,c.numero, c.numero as idfactura,
		0 ingreso,d.cantidad as egreso,c.numero,0,0,0,0,0,0,0
		FROM itstra as d
		JOIN stra as c on d.numero=c.numero
		WHERE envia<>'INFI' and tipo_doc='FC' and c.numero='$id'");
		
		$mSQL=$CI->db->query("SELECT c.recibe as almacen,d.codigo,DATE_FORMAT(c.fecha,'%Y%m') fecha,'TE' as origen,'ingreso' caso,c.fecha as fechac
		FROM itstra as d
		JOIN stra as c on d.numero=c.numero
		WHERE  envia<>'INFI' and c.numero='$id'
		UNION
		SELECT c.envia as almacen,d.codigo,DATE_FORMAT(c.fecha,'%Y%m') fecha,'TS' as origen,'egreso' caso,c.fecha as fechac
		FROM itstra as d
		JOIN stra as c on d.numero=c.numero
		WHERE envia<>'INFI' and c.numero='$id'");
		
		foreach($mSQL->result() as $items ){
				
			$this->_rcalcula("$items->codigo","$items->fecha","$items->origen","$items->caso","$items->almacen");
			$this->_costos("$items->codigo","$items->almacen","$items->fechac","$items->origen","$id");
		}
		
		
	}
	function _at($id){
		
		$CI =& get_instance();
		$CI->db->query("DELETE FROM costos WHERE idfactura='$id' AND origen='AT'");
		$CI->db->query("INSERT INTO costos  SELECT '02' moneda, (SELECT cambio FROM cambio as f WHERE c.fecha=f.fecha LIMIT 1) cambio,c.arribo, '0002' as ubica,'0002' as ubica2,d.codigo ,
		'AT' as origen,c.orden,c.numero,d.invcantidad as ingreso,0 egreso,c.numero,0,0,0,0,0,0,0
		FROM itordi as d
		JOIN sinv as b on d.codigo=b.codigo
		JOIN ordi as c on d.numero=c.numero
		WHERE b.tipo='01' AND c.status='A' and c.numero='$id'");
		
		$mSQL=$CI->db->query("SELECT codigo,DATE_FORMAT(c.fecha,'%Y%m') fecha,c.fecha as fechac
		FROM itordi as d
		JOIN ordi as c on d.numero=c.numero
		WHERE c.numero='$id'");
		
		foreach($mSQL->result() as $items ){
				
			$this->_rcalcula("$items->codigo","$items->fecha","AT","ingreso","0002");
			$this->_costos("$items->codigo","0002","$items->fechac","AT","$id");
		}

	}
	function _ct($id){
		$CI =& get_instance();
		$CI->db->query("DELETE FROM costos WHERE orden='$id' AND origen='CT'");
		$CI->db->query("INSERT INTO costos  SELECT c.moneda,(SELECT cambio FROM cambio as f WHERE c.fecha=f.fecha LIMIT 1) cambio,c.fecha, '0005' as ubica,'0005' as ubica2,d.codigo,
		'CT' as origen, c.numero, c.numero as idfactura,d.invcantidad as ingreso,0 egreso,c.numero,0,0,0,0,0,0,0
		FROM itordc as d
		JOIN sinv as b on d.codigo=b.codigo
		JOIN ordc as c on d.numero=c.numero
		WHERE b.tipo='01' AND c.status='T' and c.numero='$id'");
		
		$mSQL=$CI->db->query("SELECT b.codigo,DATE_FORMAT(c.fecha,'%Y%m') fecha,c.fecha as fechac
		FROM itordc as d
		JOIN sinv as b on d.codigo=b.codigo
		JOIN ordc as c on d.numero=c.numero
		WHERE b.tipo='01' and c.numero='$id'");
		
		foreach($mSQL->result() as $items ){
				
			$this->_rcalcula("$items->codigo","$items->fecha","CT","ingreso","0005");
			$this->_costos("$items->codigo","0005","$items->fechac","CT","$id");
		}
		
	}
	function _c($id){
		
		//echo 'no define';
		//SELECT c.moneda,c.cambio,c.fecha,c.almacen as ubica,c.almacen as ubica2,d.codigo ,'CE' as origen, entrada,
		//d.costo as monto, entrada*d.costo as venta,
		//c.numero as presup,c.estampa,c.numero, c.id as idfactura,b.ultimo
		//FROM itconv as d
		//JOIN sinv as b on d.codigo=b.codigo
		//JOIN conv as c on d.numero=c.numero
		//WHERE entrada>0 AND b.tipo='Articulo' AND d.codigo=mCODIGO
		//UNION
		//SELECT c.moneda,c.cambio,c.fecha,c.almacen as ubica,c.almacen as ubica2,d.codigo ,'CS' as origen, salida*-1 as salida,
		//d.costo as monto, salida*d.costo as venta,
		//c.numero as presup,c.estampa,c.numero, c.id as idfactura,b.ultimo
		//FROM itconv as d
		//JOIN sinv as b on d.codigo=b.codigo
		//JOIN conv as c on d.numero=c.numero
		//WHERE salida>0 AND  b.tipo='Articulo' AND d.codigo=mCODIGO;
	}
	
}
